{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# K-means\n",
    "\n",
    "Documentação: http://spark.apache.org/docs/1.6.3/mllib-clustering.html#k-means"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "from numpy import array\n",
    "from math import sqrt\n",
    "from pyspark import SparkContext\n",
    "from pyspark.mllib.clustering import KMeans, KMeansModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Carregando e traduzindo o dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = sc.textFile(\"data/kmeans_data.txt\")\n",
    "parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Construindo o modelo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "clusters = KMeans.train(parsedData, 2, maxIterations=10, initializationMode=\"random\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Avaliando a clusterização pela soma dos erros quadrados"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Within Set Sum of Squared Error = 0.692820323028\n"
     ]
    }
   ],
   "source": [
    "def error(point):\n",
    "        center = clusters.centers[clusters.predict(point)]\n",
    "        return sqrt(sum([x**2 for x in (point - center)]))\n",
    "\n",
    "WSSSE = parsedData.map(lambda point: error(point)).reduce(lambda x, y: x + y)\n",
    "print(\"Within Set Sum of Squared Error = \" + str(WSSSE))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sc.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Pyspark (Py 2)",
   "language": "",
   "name": "pyspark"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
